<template>
  <div class="app-container">
    <el-card style="border-radius: 10px;">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发票号码" prop="invoiceNumber">
        <el-input
          v-model="queryParams.invoiceNumber"
          placeholder="请输入发票号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发票代码" prop="invoiceCode">
        <el-input
          v-model="queryParams.invoiceCode"
          placeholder="请输入发票代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务类型" prop="businessType">
        <el-select v-model="queryParams.businessType" placeholder="请选择业务类型" clearable @clear="resetQueryBussinessType">
          <el-option v-for="item in businessType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="发票类型" prop="invoiceType">
        <el-select v-model="queryParams.invoiceType" placeholder="请选择发票类型" clearable @clear="resetQueryInvoiceType">
          <el-option v-for="item in invoiceType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户/供应商" :label-width="'120'" prop="customersOrSuppliers">
        <el-input
          v-model="queryParams.customersOrSuppliers"
          placeholder="请输入客户或供应商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="请选择时间范围" :label-width="'220'" prop="startDate">
        <el-date-picker
          v-model="queryParams.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <div style="height:20px"></div>
    <el-card style="border-radius: 10px;">
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['financial:invoiceInquiry:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['financial:invoiceInquiry:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['financial:invoiceInquiry:remove']"d
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['financial:invoiceInquiry:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="invoiceInquiryList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="发票号码" align="center" prop="invoiceNumber">
        <template slot-scope="scope">
          <!-- <el-button
            v-if="scope.row.businessType==0"
            type="text"
            @click="handleSaleView(scope.row)"
            v-hasPermi="['xs:salesInvoice:query']"
          >{{scope.row.invoiceNumber}}</el-button> -->
          <!-- <el-button
            v-if="scope.row.businessType==1"
            type="text"
            @click="handleCgView(scope.row)"
            v-hasPermi="['xs:salesInvoice:query']"
          >{{scope.row.invoiceNumber}}</el-button>
          <span v-if="scope.row.businessType==2">{{scope.row.invoiceNumber}}</span> -->
          <span>{{scope.row.invoiceNumber}}</span>
        </template>
      </el-table-column>
      <el-table-column label="发票代码" align="center" prop="invoiceCode" />
      <el-table-column label="业务类型" align="center" prop="businessType">
        <!-- <template slot-scope="scope">
          <span>{{scope.row.businessType==0?"销售":scope.row.businessType==1?"采购":scope.row.businessType==2?"报销":"未知"}}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="发票类型" align="center" prop="invoiceType">
        <!-- <template slot-scope="scope">
          <span>{{scope.row.invoiceType==4?"收据":scope.row.invoiceType==0?"普通发票":scope.row.invoiceType==1?"专用发票":scope.row.invoiceType==2?"红字普通发票":scope.row.invoiceType==3?"红字专用发票":"未知"}}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="客户/供应商" align="center" prop="customersOrSuppliers" />
      <el-table-column label="人员" align="center" prop="staff" />
      <el-table-column label="日期" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.businessType=='销售'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSaleView(scope.row)"
            v-hasPermi="['financial:invoiceInquiry:edit']"
          >查看</el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleView(scope.row)"
            v-hasPermi="['financial:invoiceInquiry:edit']"
          >查看</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['financial:invoiceInquiry:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['financial:invoiceInquiry:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>

    <!-- 添加或修改发票查询对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发票号码" prop="invoiceNumber">
          <el-input v-model="form.invoiceNumber" placeholder="请输入发票号码" />
        </el-form-item>
        <el-form-item label="发票代码" prop="invoiceCode">
          <el-input v-model="form.invoiceCode" placeholder="请输入发票代码" />
        </el-form-item>
        <el-form-item label="业务类型" prop="businessType">
          <el-select v-model="form.businessType" placeholder="请选择业务类型">
            <el-option label="请选择" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="发票类型" prop="invoiceType">
          <el-select v-model="form.invoiceType" placeholder="请选择发票类型(0 普通发票  1 专用发票  2 红字普通发票  3 红字专用发票   4 收据)">
            <el-option label="请选择" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户或供应商" prop="customersOrSuppliers">
          <el-input v-model="form.customersOrSuppliers" placeholder="请输入客户或供应商" />
        </el-form-item>
        <el-form-item label="人员" prop="staff">
          <el-input v-model="form.staff" placeholder="请输入人员" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 查看销售发票明细对话框 -->
    <el-dialog :title="title" :visible.sync="saleOpen" width="1300px" append-to-body>
      <el-form ref="saleForm" :model="saleForm" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户ID" prop="clientId" style="display: none;">
              <el-input v-model="saleForm.clientId" placeholder="请输入客户ID" />
            </el-form-item>
            <el-form-item label="客户编码" prop="clientCode" style="display: none;">
              <el-input v-model="saleForm.clientCode" placeholder="请输入客户编码" />
            </el-form-item>
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="saleForm.clientName" readonly>
                <el-button
                  slot="append"
                  @click="handleSelectClient"
                  icon="el-icon-search"
                  v-if="saleOptType === 'add'"
                >
                </el-button>
              </el-input>
              <ClientSelect ref="clientSelect" @onSelected="onClientSelected" ></ClientSelect>
            </el-form-item>
            <el-form-item label="客户简称" prop="clientNick" style="display: none;">
              <el-input v-model="saleForm.clientNick" placeholder="请输入客户简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票人" prop="invoicePerson">
              <el-input v-model="saleForm.invoicePerson" placeholder="请输入开票人" :readonly="saleOptType === 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-select v-model="saleForm.invoiceType" placeholder="请选择发票类型" :disabled="saleOptType === 'view'">
                <el-option label="收据" value="收据" />
                <el-option label="普通发票" value="普通发票" />
                <el-option label="专用发票" value="专用发票" />
                <el-option label="红字普通发票" value="红字普通发票" />
                <el-option label="红字专用发票" value="红字专用发票" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker
                clearable
                v-model="saleForm.invoiceDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择开票日期"
                :disabled="saleOptType === 'view'"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center" class="custom-divider">开票信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发票抬头" prop="invoiceHeader">
              <el-input v-model="saleForm.invoiceHeader" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="纳税人识别号" prop="taxpayerNumber">
              <el-input v-model="saleForm.taxpayerNumber" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地址" prop="address">
              <el-input v-model="saleForm.address" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开户行" prop="openingBank">
              <el-input v-model="saleForm.openingBank" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开户账号" prop="openAccount">
              <el-input v-model="saleForm.openAccount" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票代码" prop="invoiceCode">
              <el-input v-model="saleForm.invoiceCode" placeholder="请输入发票代码" :readonly="saleOptType === 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input v-model="saleForm.invoiceNumber" placeholder="请输入发票号码" :readonly="saleOptType === 'view'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票金额" prop="invoiceValue">
              <el-input-number
                v-model="saleForm.invoiceValue"
                :min="0"
                :step="1"
                :precision="2"
                placeholder="请输入发票金额"
                :disabled="saleOptType === 'view'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center" class="custom-divider" v-if="saleForm.invoiceId !== null">发票明细</el-divider>
        <InvoiceLine
            ref="invoiceLine"
            :invoiceId="form.invoiceId"
            :clientId="form.clientId"
            :saleOptType="saleOptType"
            v-if="form.invoiceId !== null"
        ></InvoiceLine>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="handleConfirm" v-if="saleOptType === 'edit'">提 交</el-button>
        <el-button type="primary" @click="submitForm" v-if="saleOptType !== 'view'">保 存</el-button>
        <el-button @click="scaleCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listSalesInvoice,
  getSalesInvoice,
  delSalesInvoice,
  addSalesInvoice,
  updateSalesInvoice } from "@/api/mes/xs/salesInvoice";
import {
  listInvoice,
  getInvoice,
  delInvoice,
  addInvoice,
  updateInvoice,
  listReceipt,
  confirmInvoice,
  getTaxRateSelectData
} from "@/api/mes/cg/invoice";
import { listInvoiceInquiry, getInvoiceInquiry, delInvoiceInquiry, addInvoiceInquiry, updateInvoiceInquiry } from "@/api/mes/financial/invoiceInquiry";
import ClientSelect from "@/components/clientSelect/single.vue";
import InvoiceLine from "../../xs/salesInvoice/line.vue";

export default {
  name: "InvoiceInquiry",
  components: {
    ClientSelect,
    InvoiceLine
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      salesInvoiceList:[],
      cgInvoiceList:[],
      businessType:[
        {value:'销售',label:'销售'},
        {value:'采购',label:'采购'}
      ],
      invoiceType:[
        {value:"普通发票",label:"普通发票"},
        {value:"专用发票",label:"专用发票"},
        {value:"红字普通发票",label:"红字普通发票"},
        {value:"红字专用发票",label:"红字专用发票"},
        {value:"收据",label:"收据"}
      ],
      saleOptType:"",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发票查询表格数据
      invoiceInquiryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        invoiceNumber: null,        
        invoiceCode: null,        
        businessType: null,        
        invoiceType: null,        
        customersOrSuppliers: null,        
        staff: null,
        timeRange: null      
      },
      //销售发票表单参数
      saleForm: {},
      saleOpen: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        invoiceNumber: [
          { required: true, message: "发票号码不能为空", trigger: "blur" }
        ],        invoiceCode: [
          { required: true, message: "发票代码不能为空", trigger: "blur" }
        ],        businessType: [
          { required: true, message: "业务类型(0 销售   1 采购  2 报销)不能为空", trigger: "change" }
        ],        invoiceType: [
          { required: true, message: "发票类型(0 普通发票  1 专用发票  2 红字普通发票  3 红字专用发票   4 收据)不能为空", trigger: "change" }
        ],        customersOrSuppliers: [
          { required: true, message: "客户或供应商不能为空", trigger: "blur" }
        ],        staff: [
          { required: true, message: "人员不能为空", trigger: "blur" }
        ]      }
    };
  },
  async created() {
    // await addInvoiceInquiry(this.form).then(response => {});
    this.getList();
  },
  methods: {
     /** 查询发票查询列表 */
     getList() {
      this.loading = true;
      listInvoiceInquiry(this.queryParams).then(response => {
        this.invoiceInquiryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    formatDateForDB(dateStr) {
      const date = new Date(dateStr);
      const pad = num => num.toString().padStart(2, '0');
      
      return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    },
    /** 发票数据 */
    async synchronizeData() {
      this.loading = true;

      await listSalesInvoice().then(response => { //销售发票list
        this.salesInvoiceList = response.rows;
      });

      await listInvoice().then(response => { //采购发票list
        this.cgInvoiceList = response.rows;
      });
      
      console.log(this.salesInvoiceList);
      console.log(this.cgInvoiceList);

      await this.salesInvoiceList.forEach(item => { 

            this.form.invoiceNumber = item.invoiceNumber;
            this.form.invoiceCode = item.invoiceCode;
            this.form.businessType = "销售";
            this.form.invoiceType = item.invoiceType=="普通发票"?"0" : item.invoiceType=="专用发票"?"1" : item.invoiceType=="红字普通发票"?"2" : item.invoiceType=="红字专用发票"?"3" : item.invoiceType=="收据"?"4":"位置类型";
            this.form.customersOrSuppliers = item.clientName;
            this.form.staff = item.invoicePerson;
            this.form.createTime = item.createTime;
            const isExist = this.invoiceInquiryList.some(item => 
             item.invoiceNumber === this.form.invoiceNumber
            );
            alert(isExist);
            if(!isExist){
              addInvoiceInquiry(this.form).then(response => {});
            }
            
      });

      // await this.cgInvoiceList.forEach(item => { 
      //       addInvoiceInquiry(this.form).then(response => {
      //       });
      // });

      
      await listInvoiceInquiry(this.queryParams).then(response => {
        this.invoiceInquiryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        attr1: null,        attr2: null,        attr3: null,        attr4: null,        tenantId: null,        invoiceNumber: null,        invoiceCode: null,        businessType: null,        invoiceType: null,        customersOrSuppliers: null,        staff: null      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.queryParams.timeRange!=null){
          this.queryParams.timeRange[0]=this.formatDateForDB(this.queryParams.timeRange[0]);
          this.queryParams.timeRange[1]=this.formatDateForDB(this.queryParams.timeRange[1]);
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.timeRange=null;
      this.handleQuery();
    },
    resetQueryBussinessType() {
      this.queryParams.businessType=null;
    },
    resetQueryInvoiceType() {
      this.queryParams.invoiceType=null;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加发票查询";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInvoiceInquiry(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改发票查询"; 
      });
    },
    handleSaleView(data){
      getSalesInvoice(data.sourceId).then(response => {
        response.data.url?window.open(response.data.url):this.$modal.msgWarning("暂未上传发票！");
      });
    },
    handleView(data){
      getInvoice(data.sourceId).then(response => {
        response.data.invoiceUrl?window.open(response.data.invoiceUrl):this.$modal.msgWarning("暂未上传发票！");
      });
    },
    // handleSaleView(row) {
    //   this.saleReset();
    //   getSalesInvoice(row.sourceId).then(response => {
    //     this.saleForm = response.data;
    //     this.saleOpen = true;
    //     this.saleOptType = 'view'
    //   });
    // },
    // 销售表单重置
    saleReset() {
      this.saleForm = {
        invoiceId: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        clientNick: null,
        invoiceType: null,
        invoicePerson: null,
        invoiceDate: new Date(),
        invoiceHeader: null,
        taxpayerNumber: null,
        address: null,
        openingBank: null,
        openAccount: null,
        invoiceCode: null,
        invoiceNumber: null,
        invoiceValue: null,
        invoiceStatus: "未确认",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("saleForm");
    },
    //客户选择弹出框
    onClientSelected(obj){
      if(obj !== undefined && obj !== null){
        this.saleForm.clientId = obj.clientId;
        this.saleForm.clientCode = obj.clientCode;
        this.saleForm.clientName = obj.clientName;
        this.saleForm.clientNick = obj.clientNick;
        this.saleForm.invoiceHeader = obj.clientName;
        this.saleForm.taxpayerNumber = obj.creditCode;
        this.saleForm.address = obj.address;
        this.saleForm.openingBank = obj.openBank;
        this.saleForm.openAccount = obj.openAccount;
      }
    },
    // 取消按钮
    scaleCancel() {
      this.saleOpen = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInvoiceInquiry(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInvoiceInquiry(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除发票查询编号为"' + ids + '"的数据项？').then(function() {
        return delInvoiceInquiry(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('financial/invoiceInquiry/export', {
        ...this.queryParams
      }, `invoiceInquiry_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
